<?php

namespace Common\Commission;

use Think\Log;

class MixtureAdapter {

    public $_error = "";

    public function assign($order_id, $commission_level = 0, $commission_scale = "", $assign_scale = 100) {

        if (empty($order_id)) {
            return false;
        }

        if (is_string($commission_scale)) {
            $commission_scale = explode("|", $commission_scale);
        }

        if (!is_array($commission_scale)) {
            return false;
        }

        $this->commission($order_id, $commission_level, $commission_scale, $assign_scale);
    }

    private function commission($orderno, $commission_level, $commission_scale, $assign_scale) {

        $omap ['no'] = array("eq", $orderno);
        $omap ['pay_status'] = array("eq", 2);
        $omap ['status'] = array("eq", 1);
        $order = D("Order")->where($omap)->find(); //获取满足条件的订单
        if (empty($order)) {
            $this->_error = ("订单编号:$orderno，分佣失败，订单信息不存在");
            return false;
        }
        $member_model = D("Member");
        $current_member = $member_model->find($order['userid']);

        if (empty($current_member)) {
            $this->_error = ("订单编号:$orderno，分佣失败，订单用户不存在");
            return false;
        }
        if ($current_member['id'] == $current_member['flag']) {
            $this->_error = ("订单编号:$orderno，分佣失败，顶级用户无法分佣");
            return false;
        }
        $top_member = $member_model->find($current_member['flag']);
        if (empty($top_member)) {
            $this->_error = ("订单编号:$orderno，分佣失败，用户关系不存在");
            return false;
        }
        $order_goods = D("OrderGoods")->where(array("order_id", $order['id']))->select();
        if (empty($order_goods)) {
            $this->_error = ("订单编号:$orderno，分佣失败，订单内容不存在");
            return false;
        }

        $tmap["lft"] = array('between', array($top_member['lft'], $current_member['lft']));
        $tmap["rgt"] = array('between', array($current_member['rgt'], $top_member['rgt']));
        $tmap["id"] = array('neq', $current_member['id']);

        $tree_users = $member_model->where($tmap)->order("lft desc")->select();

        $commission_list = array();
        $pids = array();
        foreach ($order_goods as $goods) {
            if (($goods["commission_sacle"] + $assign_scale) > 100) {
                $this->_error = ("订单编号:$orderno，分佣失败，分配比例出错，已经分配比例为：" .
                        $goods["commission_sacle"] . "本次请求分配比例为：$assign_scale");
                return false;
            }

            $commission_total = $goods['commission'] * ($assign_scale / 100);
            $commission_total_fact = $goods['commission'];
            $pids[] = $goods['pid'];
            $tmp = 0.0;
            for ($index = 0; $index < $commission_level; $index++) {
                $scale = 0;
                if (isset($commission_scale[$index])) {
                    $scale = $commission_scale[$index];
                }

                $commission = $commission_total * ($scale / 100);
                $tmp += $commission;
                $cm = NULL;
                if (isset($tree_users[$index])) {
                    $cm = $tree_users[$index];
                }
                if (($goods['commission_status'] == 0) || ($goods['commission_sacle'] < 100)) {
                    $time = time();
                    $commission_list[] = array(
                        "userid" => $cm['id'],
                        "order_no" => $orderno,
                        "commission" => $commission,
                        "commission_total" => $commission_total,
                        "commission_total_fact" => $commission_total_fact,
                        "commission_scale" => $scale,
                        "assign_scale" => $assign_scale,
                        "customer" => $order['userid'],
                        "goods" => $goods['pid'],
                        "create_time" => $time,
                        "update_time" => $time,
                    );

                    Log::write("用户" . $cm['openid'] . ",分佣比例为" .
                            $scale . ",获得佣金" . $commission .
                            ",已经发放$tmp" . ",总佣金为$commission_total,发放时间" . date("Y-m-d h:i:s", $time));

                    echo "用户" . $cm['openid'] . ",分佣比例为" .
                    $scale . ",获得佣金" . $commission .
                    ",已经发放$tmp" . ",总佣金为$commission_total,发放时间" . date("Y-m-d h:i:s", $time);
                    echo "<br>";
                } else {
                    $this->_error = ("订单编号:$orderno，分佣失败，产品" . $goods['pid'] . "佣金已经发放过了");
                }
            }
        }
        exit;
        //存储佣金发放信息
        if (count($commission_list) > 0) {
//        dump($commission_list);
            $res = D("MemberCommission")->addAll($commission_list);

            echo M()->getLastSql();
            echo "<br>";
            $this->_error = ("佣金:" . M()->getLastSql());
            if ($res) {
                $dg_map['order_id'] = array("eq", $orderno);
                $dg_map['pid'] = array("in", $pids);


                D("OrderGoods")->where($dg_map)->setField('commission_status', 1);
                D("OrderGoods")->where($dg_map)->setInc('commission_sacle', $assign_scale);
//        echo M()->getLastSql();
//                if ($us) {
                $this->_error = ("佣金已经发放：" . json_encode($commission_list));

                return $commission_list;
//                } else {
//                    $commission_map['customer'] = array("eq", $order['userid']);
//                    $commission_map['order_no'] = array("eq", $orderno);
//                    $commission_map['goods'] = array("in", $pids);
//                    D("MemberCommission")->where($commission_map)->delete();
//                }
            } else {
                $this->_error = ("佣金发放失败");
                return false;
            }
        }

        return false;
    }

}
